#include "CServer.h"
#include "AsioIOServicePool.h"
#include "HttpConnection.hpp"

CServer::CServer(boost::asio::io_context &ioc, unsigned short &port)
    : _ioc(ioc), _acceptor(ioc, tcp::endpoint(tcp::v4(), port))
{
}

void CServer::Start()
{
    auto self = shared_from_this();
    auto &io_context = AsioIOServicePool::GetInstance()->GetIOService();    //获取一个较空闲的io_context
    //获取一个新的http连接(内部使用io_context构造socket，监听事件)
    std::shared_ptr<HttpConnection> new_con = std::make_shared<HttpConnection>(io_context);
	//通过下面的代码进行异步监听新链接，每次接受完新连接后就继续监听
    _acceptor.async_accept(new_con->GetSocket(), [self, new_con](beast::error_code ec)
                            {
	try {
		//出错则放弃这个连接，继续监听新链接
		if (ec) {
            //重新投递一个事件，并不是递归
			self->Start();
			return;
		}

		//继续监听
		self->Start();
		//处理新链接，创建HpptConnection类管理新连接
		new_con->Start();
	}
	catch (std::exception& exp) {
		std::cout << "exception is " << exp.what() << std::endl;
		self->Start();
	} 
    });
}
